package com.lanou3g.code0416;

import java.io.*;

/**
 * Created by dllo on 18/4/16.
 */
public class Test03 {
    public static void main(String[] args) {
        read();
        write();
    }

    public static void write() {
        File file= new File("test.txt");
        //BufferedWriter还是不方便
        //写文本的时候  通常使用PrintWriter
        PrintWriter pw = null;
        OutputStreamWriter osw =null;
        FileOutputStream fos = null;

        try {
            //是否是追加模式
            //根据FileoutputStream来走
            //在即一个true参数  就是追加模式
            fos=new FileOutputStream(file);
            osw=new OutputStreamWriter(fos);
            pw= new PrintWriter(osw);
            pw=new PrintWriter(
                    new OutputStreamWriter(
                            new FileOutputStream(file)));
            //写入文件的时候
            //用法跟System.out一样

//            pw.println(1);
//            pw.println(2);
//            pw.println(3);
//            pw.println(4);
//            pw.println(5);
            pw.flush();
            //全部写完之后,务必加上flush
            //养成好习惯

        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            IOUtils.closeAll(pw);
        }
    }

    //使用字符流读取文本信息
    public static void read() {
        File file = new File("test.txt");
        BufferedReader reader = null;
        InputStreamReader isr = null;
        FileInputStream fis = null;

        try {
            fis = new FileInputStream(file);
            isr = new InputStreamReader(fis);
            reader = new BufferedReader(isr);
            String line = "";
            StringBuilder sb = new StringBuilder();
            while ((line = reader.readLine()) != null) {//readline  换行
                /*
                如果最后的结果
                想要保留换行信息
                则需要手动拼接换行
                大多数情况下 都不需要
                 */
                sb.append(line).append("\n");
                System.out.println("->" + line);
            }
            String result = sb.toString();
            System.out.println(result);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            IOUtils.closeAll(reader);
        }
    }
}
